package com.nageoffer.jobtrain.judge.common.config;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * docker代码沙箱配置类
 * author：唐晨
 */
@Configuration
public class DockerSandBoxPoolConfiguration {
    /**
     * docker主机地址
     */
    @Value("${sand-box.docker.host}")
    private String dockerHost;

    /**
     * 限制使用内存
     */
    @Value("${sand-box.limit.memory}")
    private Long memoryLimit;

    /**
     * 限制交互分区内存
     */
    @Value("${sand-box.limit.memory-swap}")
    private Long memorySwapLimit;

    /**
     * 限制CPU资源
     */
    @Value("${sand-box.limit.cpu}")
    private Long cpuLimit;

    /**
     * docker jdk镜像名称
     */
    @Value("${sand-box.docker.image}")
    private String sandboxImage;

    /**
     * 数据库挂载位置
     */
    @Value("${sand-box.docker.volume}")
    private String volumeDir;

    /**
     * docker 容器池容器数量
     */
    @Value("${sand-box.docker.pool-size}")
    private int poolSize;

    /**
     * 容器命名前缀
     */
    @Value("${sand-box.docker.name-prefix}")
    private String containerNamePrefix;

    /**
     * 创建 docker客户端
     *
     * @return docker客户端
     */
    @Bean
    public DockerClient dockerClient() {
        DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(dockerHost)
                .build();
        return DockerClientBuilder
                .getInstance(clientConfig)
                .withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
                .build();
    }

    /**
     * 创建 docker容器池
     *
     * @param dockerClient docker客户端
     * @return docker容器池
     */
    @Bean
    public DockerSandBoxPool dockerSandBoxPool(DockerClient dockerClient) {
        DockerSandBoxPool dockerSandBoxPool = new DockerSandBoxPool(dockerClient, sandboxImage, volumeDir, memoryLimit,
                memorySwapLimit, cpuLimit, poolSize, containerNamePrefix);
        dockerSandBoxPool.initDockerSandBoxPool();
        return dockerSandBoxPool;
    }
}
